//
//  MallAddressViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/9/2.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "MallAddressViewController.h"
#import "MallAddressTableViewCell.h"
#import "MallEditAddressViewController.h"
#import "Address.h"

@interface MallAddressViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSMutableArray *addressArr;

@end

@implementation MallAddressViewController {
    UITableView         *_tableView;
    MallAddressTableViewCell    *_cell;
}

- (void)viewWillAppear:(BOOL)animated {
    
    [self GETAddress];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createUI];
    
    
}


#pragma mark ==========构建UI==========
- (void)createUI {
    
    self.navigationItem.title = @"收货地址管理";
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-49) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    [_tableView registerNib:[UINib nibWithNibName:@"MallAddressTableViewCell" bundle:nil] forCellReuseIdentifier:@"mall"];
    
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:addBtn];
    [addBtn setTitle:@"新增收货地址" forState:UIControlStateNormal];
    [addBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [addBtn setBackgroundColor:UIMainColorRGB];
    addBtn.titleLabel.font = kUHSystemFontWithSize(16);
    addBtn.frame = CGRectMake(0, SCREEN_HEIGHT-64-49, SCREEN_WIDTH, 49);
    [addBtn addTarget:self action:@selector(addAddressClick:) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    _cell = [tableView dequeueReusableCellWithIdentifier:@"mall"];
    
    Address *model = self.addressArr[indexPath.row];
    _cell.model = model;
    
    _cell.defaultAddress.tag = indexPath.row+1;
    [_cell.defaultAddress addTarget:self action:@selector(defaultAddressClick:) forControlEvents:UIControlEventTouchUpInside];
    _cell.editAddress.tag = indexPath.row+1;
    [_cell.editAddress addTarget:self action:@selector(editAddressClick:) forControlEvents:UIControlEventTouchUpInside];
    _cell.deleteAddress.tag = indexPath.row+1;
    [_cell.deleteAddress addTarget:self action:@selector(deleteAddressClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return _cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.addressArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return [_cell cellHeight];
    return _cell.line2.y+10;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
    
    Address *model = self.addressArr[indexPath.row];
	
	if (![NSString isEmpty:self.orderId]) {
		NSDictionary *param = @{@"order_ids":self.orderId,
								@"address_id":[model valueForKey:@"addr_id"]};
		
		[[NetworkTool sharedTool] requestWithName:@"修改订单地址" URLString:APIMallsOrdersAddr parameters:param method:@"PUT" callBack:^(id responseObject) {
			
			[self.navigationController popViewControllerAnimated:YES];
			
			if (self.returnAddr != nil) {
				self.returnAddr(@{@"name":model.name,
								  @"mobile":model.mobile,
								  @"addr":[NSString stringWithFormat:@"%@%@%@%@", model.province, model.city, model.district, model.detail]});
			}
			
		}];
	}
}

- (void)returnAddress:(ReturnAddressBlock)block {
    self.returnAddr = block;
}
#pragma mark ==========响应方法==========
// 获取收货地址
- (void)GETAddress {
    
    // GET /users/receive-addresses 获取收货地址
//#define APIReceiveAddresses            [APIUser stringByAppendingString:@"/receive-addresses"]
    [[NetworkTool sharedTool] requestWithName:@"获取收货地址" URLString:APIReceiveAddresses parameters:nil method:@"GET" callBack:^(id responseObject) {
       
        NSArray *arr = responseObject[@"data"];
        [self.addressArr removeAllObjects];
        
        for (NSDictionary *dic in arr) {
            Address *model = [[Address alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.addressArr addObject:model];
        }
        
        [_tableView reloadData];
        
    }];
    
}
// 修改收货地址
- (void)defaultAddressClick:(UIButton *)sender {
    Address *model = self.addressArr[sender.tag-1];
    NSString *url = [NSString stringWithFormat:@"%@/%ld", APIReceiveAddresses, model.addr_id];
    NSDictionary *param;
    if (model.is_default == 1) {
        param = @{@"is_default":@"0"};
    }
    else
        param = @{@"is_default":@"1"};
   
    [[NetworkTool sharedTool] requestWithName:@"修改默认地址" URLString:url parameters:param method:@"PUT" callBack:^(id responseObject) {
        
        [self GETAddress];
        
    }];
}
- (void)editAddressClick:(UIButton *)sender {
    MallEditAddressViewController *editVC = [[MallEditAddressViewController alloc] init];
    editVC.model = self.addressArr[sender.tag-1];
    editVC.type = 1;
    [self.navigationController pushViewController:editVC animated:YES];
    
}
- (void)deleteAddressClick:(UIButton *)sender {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否删除地址" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        Address *model = self.addressArr[sender.tag-1];
        NSString *url = [NSString stringWithFormat:@"%@/%ld", APIReceiveAddresses, model.addr_id];
        [[NetworkTool sharedTool] requestWithName:@"删除收货地址" URLString:url parameters:nil method:@"DELETE" callBack:^(id responseObject) {
            
            [self GETAddress];
            
        }];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
    
}



- (void)addAddressClick:(UIButton *)sender {
    NSLog(@"点击新增收货地址");
    MallEditAddressViewController *editVC = [[MallEditAddressViewController alloc] init];
    editVC.type = 0;
    [self.navigationController pushViewController:editVC animated:YES];
}


// 懒加载
- (NSMutableArray *)addressArr {
    if (_addressArr == nil) {
        _addressArr = [[NSMutableArray alloc] init];
    }
    return _addressArr;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
